library(SDMTools)
library(gdistance)
library(maptools)

#set the working directory
wd='/home/jc165798/ttt/shapefile/albers/';setwd(wd)

### 01. Read in and prepare necessary data
#read in the nearshore ascii
tasc=read.asc('nearshore15km.asc')

#convert ascii to raster format for analyses
rast=raster.from.asc(tasc)

#read in the species population points - columns of interest are 'POINT_X', 'POINT_Y'
pop=read.dbf('shoreline_pops.dbf')
coords=pop[,c('POINT_X','POINT_Y')] #subset only the xy coords to be used in costDistance
coords=as.matrix(coords) #needs to be a matrix for costDistance

### 02. Calculate least cost distance using example from 'costDistance' in gdistance package.

#create a Transition object from the raster
tr=transition(rast, function(x) 1/mean(x),8)

#find least cost distance between all coords
tt=costDistance(tr,coords) #costDistance returns number of pixels between populations
tt=as.matrix(tt) #convert output to matrix
tt=tt*0.5 #multiply the entire matrix by 0.5 because each pixel is 500m to get distance
tt=cbind(as.numeric(colnames(tt)),tt) #bind populations to the rows

write.csv(tt, '/home/jc148322/Barra/Genetics/dist.csv', row.names=F)


